from itsdangerous import BadData
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from django.conf import settings

#加密
def generate_access_token(token):
    """
    签名微博token
    :param openid: 用户的openid
    :return: access_token
    """
    serializer = Serializer(settings.SECRET_KEY, expires_in=3600)
    data = {'token': token}
    token = serializer.dumps(data)
    return token.decode()
#解密
def check_access_token(token_sign):
    """
    提取openid
    :param token_sign: 签名后的openid
    :return: openid or None
    """
    serializer = Serializer(settings.SECRET_KEY, expires_in=3600)
    try:
        data = serializer.loads(token_sign)
    except BadData:
        return None
    else:
        return data.get('token')